package com.ling.pl.core.commons.springmvc;

import com.ling.pl.core.commons.exception.BusinessException;
import com.ling.pl.core.commons.springmvc.constant.FailStatus;
import com.ling.pl.core.commons.springmvc.constant.ResultStatus;
import com.ling.pl.core.commons.utils.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by bo.wang on 2016/9/27.
 * <p>
 * 不能捕获的情况如下
 * <p>
 * {
 * "timestamp": 1474982715594,
 * "status": 404,
 * "error": "Not Found",
 * "message": "No message available",
 * "path": "/legalEITInf/findByPage"
 * }
 */
public class ResposeInfo<T> {
    /**
     * 响应状态
     * link ResultStatus
     */
    int status;
    /**
     * StringUtils.getExceptionStackMessage(e)
     */
    String error;
    /**
     * 对应status,表示服务器是否有异常抛出,没有时为true,有异常时为false
     */
    boolean success = true;
    /**
     * 错误码
     * link FailStatus
     */
    private Integer errorCode;
    /**
     * e.getMessage()
     */
    private String message;
    /**
     * 请求url
     */
    private String url;
    /**
     * 返回的数据,void时为null
     */
    private T data;

    public static ResposeInfo<String> buildException(Exception e, ServletRequest req) {
        ResposeInfo<String> r = new ResposeInfo<>();
        r.setStatus(ResultStatus.FAIL);
        r.setMessage(e.getMessage());
        r.setError(StringUtils.getExceptionStackMessage(e));
        r.setSuccess(false);
        if (e instanceof BusinessException) {
            r.setErrorCode(FailStatus.BUSINESSEXCEPTION);
        } else {
            r.setErrorCode(FailStatus.INNEREXCEPTION);
        }
        e.printStackTrace();
        if (req != null && req instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) req;
            r.setUrl(httpServletRequest.getRequestURL().toString());
        }
        return r;
    }

    public static ResposeInfo<String> buildException(Exception e) {
        return buildException(e, null);
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public Integer getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }
}
